package cn.ren.cloud.mq.consumer;

import cn.ren.cloud.domain.CourseOrder;
import cn.ren.cloud.domain.PayOrder;
import cn.ren.cloud.dto.CourseOrderPayDto;
import cn.ren.cloud.enums.GlobelExceptionEnum;
import cn.ren.cloud.exception.GlobalCustomException;
import cn.ren.cloud.feign.OrderFeignClient;
import cn.ren.cloud.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "pay-order-consumer-group",
        topic = "pay-order-timeout-topic",
        selectorExpression = "pay-order-timeout-tag",
        messageModel = MessageModel.BROADCASTING)
public class CourseOrderConsumer implements RocketMQListener<MessageExt> {

    private final IPayOrderService payOrderService;
    private final OrderFeignClient orderFeignClient;

    public CourseOrderConsumer(IPayOrderService payOrderService, OrderFeignClient orderFeignClient) {
        this.payOrderService = payOrderService;
        this.orderFeignClient = orderFeignClient;
    }

    /**
     * 支付超时消息消费者
     *
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 获取内容
            byte[] body = messageExt.getBody();
            // 如果内容为空，抛出异常
            if (body.length == 0) {
                log.error("消息有问题,问题消息是：消息都没有，办不了事啊");
                throw new GlobalCustomException(GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR);
            }
            // 将数组转换为string类型，赋值给dto
            CourseOrderPayDto courseOrderPayDto = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayDto.class);
            // 获取订单号
            String orderNo = courseOrderPayDto.getOrderNo();
            PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
            if (payOrder == null) {
                return;
            }
            // 查询支付宝订单是否支付
            AlipayTradeQueryResponse query = Factory.Payment.Common().query(orderNo);
            // 获取订单状态
            String tradeStatus = query.getTradeStatus();
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                log.info("正在支付");
            } else {
                log.info("关闭支付订单");
                // @TODO 2.修改订单状态,写订单的feign接口，根据订单号修改订单状态为取消
//                CourseOrder courseOrder = orderFeignClient.selectByOrderNo(orderNo);
//                courseOrder.setStatusOrder(PayOrder.CANCEL_PAY);

                Factory.Payment.Common().cancel(orderNo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("支付超时处理失败啦···");
            throw new GlobalCustomException(GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR);
        }
    }
}
